package com.uchedao.vehicledetection.view.carlist.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.view.carlist.Entity.CarSeries;

import java.util.ArrayList;


/**
 * Created by ZhangZhanghua on 2015/8/26 0026.
 */
public class SeriesAdapter extends BaseAdapter {
    private Context mContext;
    private LayoutInflater mInflater;
    private ArrayList<CarSeries> seriesList;

    public SeriesAdapter(Context context , ArrayList<CarSeries> list){
        mContext = context;
        mInflater = LayoutInflater.from(context);
        seriesList = list;
    }
    @Override
    public int getCount() {
        return seriesList.size();
    }

    @Override
    public Object getItem(int position) {
        return seriesList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView ==null){
            convertView = mInflater.inflate(R.layout.list_item, null);
            viewHolder = new ViewHolder();
            viewHolder.tvLetter = (TextView) convertView.findViewById(R.id.catalog);
            viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.title);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        int section = getSectionForPosition(position);

        if(position == getPositionForSection(section)){
            viewHolder.tvLetter.setVisibility(View.VISIBLE);
            viewHolder.tvLetter.setText((seriesList.get(position).getSpell().toUpperCase().charAt(0)+""));
        }else{
            viewHolder.tvLetter.setVisibility(View.GONE);
        }

        viewHolder.tvTitle.setText(seriesList.get(position).getName());
        return convertView;
    }

    public int getSectionForPosition(int position) {
        return seriesList.get(position).getSpell().toUpperCase().charAt(0);
    }

    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = seriesList.get(i).getSpell().toUpperCase();
            char firstChar = sortStr.charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }


    private final class ViewHolder
    {
        TextView tvLetter;
        TextView tvTitle;
    }
}

